// 获取DOM元素
const imagePreview = document.getElementById('imagePreview');
const sizeSelect = document.getElementById('sizeSelect');
const convertBtn = document.getElementById('convertBtn');
const dragDrop = document.getElementById('dragDrop');
const fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = 'image/png,image/jpeg,image/gif,image/webp';
fileInput.style.display = 'none';
document.body.appendChild(fileInput);

// 点击上传事件
dragDrop.addEventListener('click', () => fileInput.click());

// 处理文件选择
fileInput.addEventListener('change', () => {
    if (fileInput.files.length > 0) {
        const file = fileInput.files[0];
        if (!file.type.match('image/png') && !file.type.match('image/jpeg') && !file.type.match('image/gif') && !file.type.match('image/webp')) {
            alert('仅支持PNG、JPG、GIF和WEBP格式文件');
            return;
        }
        handleFileUpload(file);
    }
});

// 拖拽上传事件
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
    dragDrop.addEventListener(eventName, preventDefaults, false);
});

// 高亮拖拽区域
['dragenter', 'dragover'].forEach(eventName => {
    dragDrop.addEventListener(eventName, highlight, false);
});

['dragleave', 'drop'].forEach(eventName => {
    dragDrop.addEventListener(eventName, unhighlight, false);
});

// 处理拖放文件
dragDrop.addEventListener('drop', function(e) {
    const dt = e.dataTransfer;
    const file = dt.files[0];
    
    // 验证文件类型
    if (!file) {
        dragDrop.classList.add('error');
        dragDrop.querySelector('p').textContent = '请拖放有效的文件格式';
        setTimeout(() => {
            dragDrop.classList.remove('error');
            dragDrop.querySelector('p').textContent = '拖拽有效文件到此处上传';
        }, 2000);
        return;
    }
    
    if (!file.type.match('image/png') && !file.type.match('image/jpeg') && !file.type.match('image/gif') && !file.type.match('image/webp')) {
        dragDrop.classList.add('error');
        dragDrop.querySelector('p').textContent = '仅支持PNG、JPG、GIF和WEBP格式文件';
        setTimeout(() => {
            dragDrop.classList.remove('error');
            dragDrop.querySelector('p').textContent = '拖拽PNG、JPG、GIF或WEBP文件到此处上传';
        }, 2000);
        return;
    }
    
    // 显示上传成功反馈
    dragDrop.classList.add('success');
    setTimeout(() => dragDrop.classList.remove('success'), 2000);
    
    // 显示文件名
    const fileNameElement = document.createElement('p');
    fileNameElement.className = 'file-name';
    fileNameElement.textContent = file.name;
    
    // 清除之前显示的文件名
    const existingFileName = dragDrop.querySelector('.file-name');
    if (existingFileName) {
        dragDrop.removeChild(existingFileName);
    }
    
    dragDrop.appendChild(fileNameElement);
    
    handleFileUpload(file);
}, false);

function preventDefaults(e) {
    e.preventDefault();
    e.stopPropagation();
}

function highlight() {
    dragDrop.classList.add('highlight');
}

// 处理文件上传
let currentFile = null;

function handleFileUpload(file) {
    currentFile = file;
    
    // 统一处理文件类型验证
    if (!file.type.match('image/png') && !file.type.match('image/jpeg') && !file.type.match('image/gif') && !file.type.match('image/webp')) {
        alert('仅支持PNG、JPG、GIF和WEBP格式文件\n\n请上传: .png、.jpg、.gif 或 .webp 格式的文件');
        return;
    }
    
    if (file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/gif' || file.type === 'image/webp') {
        // 创建预览图像
        const reader = new FileReader();
        reader.onload = function(e) {
            const preview = document.getElementById('imagePreview');
            preview.src = e.target.result;
            preview.style.display = 'block';
            document.getElementById('convertBtn').disabled = false;
        };
        reader.onerror = function() {
            alert('文件读取失败');
        };
        reader.readAsDataURL(file);
    }
}

function unhighlight() {
    dragDrop.classList.remove('highlight');
}

// 全尺寸复选框事件处理
const allSizesCheckbox = document.getElementById('allSizesCheckbox');
allSizesCheckbox.addEventListener('change', function() {
    convertBtn.disabled = this.checked;
    if (this.checked) {
        convertBtn.style.opacity = '0.5';
        convertBtn.style.cursor = 'not-allowed';
    } else {
        convertBtn.style.opacity = '1';
        convertBtn.style.cursor = 'pointer';
    }
});

// 全尺寸转换按钮点击事件
const allSizesBtn = document.createElement('button');
allSizesBtn.id = 'allSizesBtn';
allSizesBtn.className = 'convert-btn';
allSizesBtn.textContent = '全尺寸转换';
allSizesBtn.disabled = true;
allSizesBtn.style.opacity = '0.5';
allSizesBtn.style.cursor = 'not-allowed';
convertBtn.insertAdjacentElement('afterend', allSizesBtn);

allSizesBtn.addEventListener('click', async function() {
    if (!currentFile) {
        alert('请先拖放有效格式文件');
        return;
    }
    
    try {
        const sizes = [1024, 512, 256, 128, 64, 48, 32, 16];
        const icoBlobs = [];
        
        // 批量转换所有尺寸
        for (const size of sizes) {
            let canvas;
            
            if (currentFile.type === 'image/svg+xml') {
                canvas = await handleSvgFile(currentFile);
            } else {
                // 读取文件
                const pngDataUrl = await readFileAsDataURL(currentFile);
                
                // 创建Canvas调整尺寸
                canvas = document.createElement('canvas');
                const ctx = canvas.getContext('2d');
                
                // 加载图像
                const img = await loadImage(pngDataUrl);
                
                // 设置Canvas尺寸
                canvas.width = size;
                canvas.height = size;
                
                // 绘制图像到Canvas
                ctx.drawImage(img, 0, 0, size, size);
            }
            
            // 转换为ICO格式
            const icoBlob = await convertCanvasToIco(canvas);
            icoBlobs.push({size, blob: icoBlob});
        }
        
        // 创建ZIP压缩包
        const zip = new JSZip();
        icoBlobs.forEach(({size, blob}) => {
            zip.file(`icon_${size}x${size}.ico`, blob);
        });
        
        // 生成ZIP文件
        const zipContent = await zip.generateAsync({type: 'blob'});
        
        // 创建下载按钮
        const downloadBtn = document.createElement('button');
        downloadBtn.id = 'downloadBtn';
        downloadBtn.className = 'convert-btn';
        downloadBtn.innerHTML = `<svg class="download-icon" viewBox="0 0 24 24"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg> 下载全尺寸ICO压缩包`;
        
        // 移除旧的下载按钮
        const oldBtn = document.getElementById('downloadBtn');
        if (oldBtn && oldBtn.parentNode === document.body) {
            document.body.removeChild(oldBtn);
        }
        
        // 添加点击事件
        downloadBtn.addEventListener('click', () => {
            const url = URL.createObjectURL(zipContent);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'all_sizes_icons.zip';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        });
        
        // 添加到全尺寸转换按钮下方
        allSizesBtn.insertAdjacentElement('afterend', downloadBtn);
        
        alert('全尺寸转换成功，请点击下载按钮');
    } catch (error) {
        console.error('转换失败:', error);
        alert('转换失败: ' + error.message);
    }
});

// 转换按钮点击事件
convertBtn.addEventListener('click', async function() {
    if (!currentFile) {
        alert('请先拖放有效格式文件');
        return;
    }
    
    const size = parseInt(sizeSelect.value);
    
    try {
        let canvas;
        
        if (currentFile.type === 'image/svg+xml') {
            canvas = await handleSvgFile(currentFile);
        } else {
            // 读取文件
            const pngDataUrl = await readFileAsDataURL(currentFile);
            
            // 创建Canvas调整尺寸
            canvas = document.createElement('canvas');
            const ctx = canvas.getContext('2d');
            
            // 加载图像
            const img = await loadImage(pngDataUrl);
            
            // 设置Canvas尺寸
            canvas.width = size;
            canvas.height = size;
            
            // 绘制图像到Canvas
            ctx.drawImage(img, 0, 0, size, size);
        }
        
        // 转换为ICO格式
        const icoBlob = await convertCanvasToIco(canvas);
        
        // 创建下载按钮
        const downloadBtn = document.createElement('button');
        downloadBtn.id = 'downloadBtn';
        downloadBtn.className = 'convert-btn';
        downloadBtn.innerHTML = `<svg class="download-icon" viewBox="0 0 24 24"><path d="M19 9h-4V3H9v6H5l7 7 7-7zM5 18v2h14v-2H5z"/></svg> 下载${size}x${size} ICO文件`;
        
        // 移除旧的下载按钮
        const oldBtn = document.getElementById('downloadBtn');
        if (oldBtn && oldBtn.parentNode === document.body) {
            document.body.removeChild(oldBtn);
        }
        
        // 添加点击事件
        downloadBtn.addEventListener('click', () => {
            const url = URL.createObjectURL(icoBlob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'favicon.ico';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        });
        
        // 添加到全尺寸转换按钮下方
        allSizesBtn.insertAdjacentElement('afterend', downloadBtn);
        
        alert('转换成功，请点击下载按钮');
    } catch (error) {
        console.error('转换失败:', error);
        alert('转换失败: ' + error.message);
    }
});

// 辅助函数: 读取文件为DataURL
function readFileAsDataURL(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = () => resolve(reader.result);
        reader.onerror = reject;
        reader.readAsDataURL(file);
    });
}

// 辅助函数: 加载图像
function loadImage(src) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        img.src = src;
    });
}

// 辅助函数: 将Canvas转换为ICO格式
function convertCanvasToIco(canvas) {
    return new Promise((resolve) => {
        // 首先转换为PNG格式
        canvas.toBlob((pngBlob) => {
            // 然后转换为ICO格式
            const reader = new FileReader();
            reader.onload = function() {
                const pngData = new Uint8Array(reader.result);
                const icoData = createIcoFile(pngData, canvas.width, canvas.height);
                const icoBlob = new Blob([icoData], {type: 'image/x-icon'});
                resolve(icoBlob);
            };
            reader.readAsArrayBuffer(pngBlob);
        }, 'image/png');
    });
}

// 监听全尺寸复选框状态变化
document.getElementById('allSizesCheckbox').addEventListener('change', function() {
    const allSizesBtn = document.getElementById('allSizesBtn');
    allSizesBtn.disabled = !this.checked;
    if (!this.checked) {
        allSizesBtn.style.opacity = '0.5';
        allSizesBtn.style.cursor = 'not-allowed';
    } else {
        allSizesBtn.style.opacity = '1';
        allSizesBtn.style.cursor = 'pointer';
    }
});

// 全尺寸复选框事件处理
document.getElementById('allSizesCheckbox').addEventListener('change', function(e) {
    const sizeSelect = document.getElementById('sizeSelect');
    const convertBtn = document.getElementById('convertBtn');
    const allSizesBtn = document.getElementById('allSizesBtn');
    sizeSelect.disabled = e.target.checked;
    convertBtn.disabled = e.target.checked;
    allSizesBtn.disabled = !e.target.checked;
});

function createIcoFile(pngData, width, height) {
    // ICO文件头 (6 bytes)
    const header = new Uint8Array([0, 0, 1, 0, 1, 0]);
    
    // 图像目录项 (16 bytes)
    const dirEntry = new Uint8Array(16);
    new DataView(dirEntry.buffer).setUint8(0, width === 256 ? 0 : width);
    new DataView(dirEntry.buffer).setUint8(1, height === 256 ? 0 : height);
    new DataView(dirEntry.buffer).setUint32(8, pngData.length + 40, true); // PNG数据+PNG头
    new DataView(dirEntry.buffer).setUint32(12, 22, true); // 文件头+目录项大小
    
    // 创建PNG数据头 (8 bytes)
    const pngHeader = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
    
    // 合并所有数据
    const icoData = new Uint8Array(header.length + dirEntry.length + pngHeader.length + pngData.length);
    icoData.set(header, 0);
    icoData.set(dirEntry, header.length);
    icoData.set(pngHeader, header.length + dirEntry.length);
    icoData.set(pngData, header.length + dirEntry.length + pngHeader.length);
    
    return icoData;
}

function loadSvgAsImage(svgString) {
    return new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        
        const blob = new Blob([svgString], {type: 'image/svg+xml'});
        const url = URL.createObjectURL(blob);
        img.src = url;
    });
}

function handleSvgFile(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = async (e) => {
            try {
                const svgString = e.target.result;
                const img = await loadSvgAsImage(svgString);
                
                const canvas = document.createElement('canvas');
                const size = document.getElementById('sizeSelect').value;
                canvas.width = size;
                canvas.height = size;
                
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, size, size);
                
                resolve(canvas);
            } catch (error) {
                reject(error);
            }
        };
        reader.onerror = reject;
        reader.readAsText(file);
    });
}

function setupDownloadButton(blob, fileName) {
    const downloadBtn = document.getElementById('downloadBtn');
    const url = URL.createObjectURL(blob);
    
    downloadBtn.onclick = () => {
        const a = document.createElement('a');
        a.href = url;
        a.download = fileName.replace(/\.\w+$/, '') + '.ico';
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    };
}

function showSuccessMessage(fileName) {
    const successArea = document.getElementById('successArea');
    const successTitle = document.getElementById('successTitle');
    
    successTitle.textContent = `${fileName} 转换成功`;
    successArea.style.display = 'block';
}